import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import $ from 'jquery';

export default class MyLoginDialog extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            email: '',
            pass: '',
        }

        this.handleChange = this.handleChange.bind(this)
        this.handleLogin = this.handleLogin.bind(this)
    }

    handleLogin() {
        // alert('登录: email='+this.state.email+' pass='+this.state.pass)
        this.props.handleClose()
        $.ajax({
            url: '/api/LoginUser',
            method: 'POST',
            data: {
                Email: this.state.email,
                PasswordHash: this.state.pass,
            }
        }).then(res => {
            console.log('登录结果: '+JSON.stringify(res))
            if(res.IsOk){//登录成功
                this.props.login({
                    name: this.state.email,
                })
            }
        },err => {
            alert('服务器响应出错')
        })
    }

    handleChange(e){
        const t = e.target
        const name = t.name

        this.setState({
            [name]: t.value
        })
    }

    render() {
        const actions = [
            <FlatButton
                label="取消"
                primary={true}
                onClick={this.props.handleClose}
            />,
            <FlatButton
                label="登录"
                primary={true}
                // keyboardFocused={true}
                onClick={this.handleLogin}
            />,
        ];

        return (
            <Dialog
                title="Login"
                actions={actions}
                modal={false}
                open={this.props.open}
                contentStyle={{width:'350px'}}
                onRequestClose={this.props.handleClose}>

                <TextField
                    value={this.state.email}
                    hintText="Please enter email"
                    name="email"
                    onChange={this.handleChange}
                    floatingLabelText="Email"/>

                <TextField
                    value={this.state.pass}
                    hintText="Please enter password"
                    name="pass"
                    onChange={this.handleChange}
                    floatingLabelText="Password"/>

            </Dialog>
        );
    }
}